package practice.tree.four;


/**
 * @Description:
 * @Author Ammar
 * @Create 2023/8/21 20:24
 */
public class BalanceBinarySearchTree extends BinarySearchTree {
    protected void rotateLeft(TreeNode grand) {
        TreeNode parent = grand.right;
        TreeNode leftChild = parent.left;

        parent.left = grand;
        grand.right = leftChild;
        afterRoatate(grand, parent, leftChild);
    }

    protected void rotateRight(TreeNode grand) {
        TreeNode parent = grand.left;
        TreeNode rightChild = parent.right;

        parent.right = grand;
        grand.left = rightChild;
        afterRoatate(grand, parent, rightChild);
    }

    private void afterRoatate(TreeNode grand, TreeNode parent, TreeNode child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            root = parent;
        }

        if (child != null) child.parent = grand;
        grand.parent = parent;
    }
}
